package com.example.tcpLearn.tcp3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 客户端多次发送数据，服务端接收数据并返回：服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {

        System.out.println("服务端启动...");

        ServerSocket serverSocket = new ServerSocket(8888);

        Socket socket = serverSocket.accept();

        /**
         * 服务端接收客户端发送的数据
         */
        InputStream inputStream = socket.getInputStream();
        DataInputStream dataInputStream = new DataInputStream(inputStream);

        /**
         * 服务端返回数据给客户端
         */
        OutputStream outputStream = socket.getOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

        while (true) {
            /**
             * 接收数据
             * 客户端提前关闭连接	服务端 readUTF() 读取到 EOF 触发异常
             */
            String data = null;
            try {
                data = dataInputStream.readUTF();
                System.out.println("服务端已收到数据：" + data);
                System.out.println("=============================");
            } catch (Exception e) {
                System.out.println(socket.getRemoteSocketAddress() + "离开了");
                dataOutputStream.close();
                dataInputStream.close();
                socket.close();
                break;
            }

            /**
             * 返回数据
             */
            dataOutputStream.writeUTF("服务端已收到数据：" + data);
            dataOutputStream.flush();
        }

    }
}
